package com.example.farmer.wode;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.app.Dialog;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.example.farmer.Activity.CustomerServiceActivity;
import com.example.farmer.Database.BuyDatabase;
import com.example.farmer.Database.ProductPublishDatabase;
import com.example.farmer.Entity.CartItem;
import com.example.farmer.Entity.Order;
import com.example.farmer.Entity.ProductPost;
import com.example.farmer.R;

public class ConfirmOrderActivity extends AppCompatActivity {
    private static final String PRODUCT_ID = "PRODUCT_ID";
    private int productId;

    private TextView productname, productprice,method, quantityValueDialog,zongshu;
    private EditText addressView;
    private TextView productPriceView;
    private TextView freightView;
    private TextView totalView;
    private TextView submitOrderButton;
    private ImageButton back_button, quantityDecreaseButton, quantityIncreaseButton;
    private ImageView productimage;
    private ProductPost productPost;
    private BuyDatabase buyDatabase;
    private ProductPublishDatabase productPublishDatabase;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_order);

        // 初始化数据库帮助类
        buyDatabase = new BuyDatabase(this);
        productPublishDatabase = ProductPublishDatabase.getInstance(this);

        // 从Intent获取商品ID
        productId = getIntent().getIntExtra("PRODUCT_ID", -1);

        // 初始化UI组件
        initializeUIComponents();

        // 根据商品ID加载商品详情
        loadProductDetail();
    }

    private void initializeUIComponents() {

        productId = getIntent().getIntExtra(PRODUCT_ID, -1);
        back_button = findViewById(R.id.back_button);
        addressView = findViewById(R.id.address_view);
        productimage = findViewById(R.id.image);
        productname = findViewById(R.id.product_name);
        method = findViewById(R.id.method);
        productprice = findViewById(R.id.product_price);
        quantityDecreaseButton = findViewById(R.id.quantity_decrease_button);
        quantityValueDialog = findViewById(R.id.quantity_value_dialog);
        quantityIncreaseButton = findViewById(R.id.quantity_increase_button);
        productPriceView = findViewById(R.id.product_price_view);
        freightView = findViewById(R.id.freight_view);
        totalView = findViewById(R.id.total_view);
        zongshu = findViewById(R.id.zongshu);
        submitOrderButton = findViewById(R.id.submit_order_button);

        back_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish(); // 结束活动
            }
        });
    }

    private void loadProductDetail() {
        if (productId != -1) {
            productPost = productPublishDatabase.getProductPostById(productId);
            if (productPost == null) {
                // 商品信息不存在
                Toast.makeText(this, "商品信息不存在", Toast.LENGTH_SHORT).show();
                finish();
                return;
            }
            // 商品信息存在，设置UI
            setupProductUI(productPost);
        } else {
            // 无效的商品ID
            Toast.makeText(this, "无效的商品ID", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    @SuppressLint({"SetTextI18n", "DefaultLocale"})
    private void setupProductUI(ProductPost productPost) {
        // 使用Glide加载图片
        Glide.with(this)
                .load(productPost.getImageUri())
                .into(productimage);

        // 设置文本信息
        productprice.setText( "¥" +productPost.getPrices());
        productname.setText(productPost.getTitle());
        freightView.setText( "¥" + productPost.getFreight());
//        freightView.setText(String.valueOf(productPost.getFreight()));
        productPriceView.setText("¥" + productPost.getPrices());
        totalView.setText(String.format("合计：¥%.2f", productPost.getPrices() + productPost.getFreight()));
        zongshu.setText(String.format("¥%.2f", productPost.getPrices() + productPost.getFreight()));

        // 初始化购买数量
        final int[] quantity = {1};
        quantityValueDialog.setText(String.valueOf(quantity[0]));

        // 设置数量增减按钮的监听器
        quantityDecreaseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                quantity[0] = Math.max(1, quantity[0] - 1);
                quantityValueDialog.setText(String.valueOf(quantity[0]));
                updateTotalPrice(totalView, productPriceView,zongshu,productPost.getPrices(), quantity[0],productPost.getFreight());
            }
        });

        quantityIncreaseButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                quantity[0]++;
                quantityValueDialog.setText(String.valueOf(quantity[0]));
                updateTotalPrice(totalView, productPriceView,zongshu,productPost.getPrices(), quantity[0],productPost.getFreight());
            }
        });

        // 设置提交订单按钮的监听器
        submitOrderButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPaymentPasswordDialog();
            }
        });
    }

    private void showPaymentPasswordDialog() {
        final EditText paymentPasswordEditText = new EditText(this);
        paymentPasswordEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
        paymentPasswordEditText.setHint("请输入支付密码");

        new AlertDialog.Builder(this)
                .setTitle("支付密码")
                .setView(paymentPasswordEditText)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String paymentPassword = paymentPasswordEditText.getText().toString();
                        if (TextUtils.isEmpty(paymentPassword)) {
                            Toast.makeText(ConfirmOrderActivity.this, "支付密码不能为空", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        boolean isPaymentSuccessful = verifyPaymentPassword(paymentPassword);
                        saveOrderToDatabase(isPaymentSuccessful ? "已支付" : "待支付");
                        Toast.makeText(ConfirmOrderActivity.this, isPaymentSuccessful ? "支付成功" : "支付密码错误", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private boolean verifyPaymentPassword(String paymentPassword) {
        // 这里应该是网络请求验证支付密码
        // 模拟验证成功
        return "123456".equals(paymentPassword);
    }

    private void saveOrderToDatabase(String paymentStatus) {
        Order order = new Order();
        order.setProductPrice(getIntent().getDoubleExtra("PRODUCT_PRICE", 0));
        order.setQuantity(getIntent().getIntExtra("QUANTITY", 1));
        order.setFreight(getIntent().getDoubleExtra("FREIGHT", 0));
        order.setTotal(order.getProductPrice() * order.getQuantity() + order.getFreight());
        order.setAddress(getIntent().getStringExtra("ADDRESS"));
        order.setPaymentStatus(paymentStatus);
        buyDatabase.insertOrder(order);
    }

    @SuppressLint("DefaultLocale")
    private void updateTotalPrice(TextView totalView, TextView productPriceView, TextView zongshu, double productPrice, int quantity, double freight) {
        double totalPrice = productPrice * quantity + freight;
        productPriceView.setText(String.format("¥%.2f", totalPrice));
        totalView.setText(String.format("合计：¥%.2f", totalPrice));
        zongshu.setText(String.format("¥%.2f", totalPrice));

    }
}